// index.js
Page({
  data: {
    banners: [
      {
        imageUrl: 'https://tryokey.oss-cn-beijing.aliyuncs.com/blog/67a6b2dee4b0e62e721f6c861.jpg',
        title: '若天理不容，我便逆转这乾坤',
        subtitle: '若前方无路，我便踏出一条路'
      },
      {
        imageUrl: 'https://tryokey.oss-cn-beijing.aliyuncs.com/blog/year-of-the-snake-13-royalty-free-image-1734513218.png',
        title: '做万丈火焰，做逆鳞一片',
        subtitle: '祝大家蛇年大吉'
      },
      {
        imageUrl: 'https://tryokey.oss-cn-beijing.aliyuncs.com/blog/173605377929875_P30192066.jpg',
        title: '因为我们都还年轻，不知天高地厚',
        subtitle: '炭治郎'
      },

    ],
    currentSwiperIndex: 0,
    hotArticles: [],
    articles: [],
    loading: false,
    error: null,
    articleLoading: false,
    articleError: null,
    currentPage: 1,
    hasMore: true,
    buttonTop: 0,
    buttonLeft: 0,
    windowHeight: 0,
    windowWidth: 0,
    isDragging: false,
    showFullGif: false,
    pageSize: 10,
    total: 0,
    showToast: false,
    toastTitle: '',
    toastDuration: 2000,
    isLoggedIn: false
  },

  onLoad() {
    // Set custom navigation bar
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#000000'
    });

    // 获取热门文章和文章列表
    this.fetchHotArticles();
    this.fetchArticleList();

    // 获取窗口信息
    const systemInfo = wx.getSystemInfoSync();
    this.setData({
      buttonTop: systemInfo.windowHeight - 180,
      buttonLeft: systemInfo.windowWidth - 160,
      windowHeight: systemInfo.windowHeight,
      windowWidth: systemInfo.windowWidth
    });
  },

  onShow() {
    // 检查登录状态
    const token = wx.getStorageSync('token');
    this.setData({
      isLoggedIn: !!token
    });

    // ... 其他 onShow 逻辑
  },

  // 获取热门文章
  fetchHotArticles() {
    wx.request({
      url: 'https://www.haoyuming.online/api/user/article/hot',
      method: 'GET',
      success: (res) => {
        console.log('热门文章响应：', res.data);
        if (res.data.code === 200) {
          // Add unique IDs to hot articles
          const hotArticlesWithIds = res.data.data.map((article, index) => ({
            ...article,
            uniqueId: `hot-${article.id || index}`
          }));

          this.setData({
            hotArticles: hotArticlesWithIds,
            loading: false,
            error: null
          });
        } else {
          this.setData({
            error: res.data.message || '获取热门文章失败',
            loading: false
          });
        }
      },
      fail: (err) => {
        console.error('获取热门文章失败：', err);
        this.setData({
          error: '网络错误，请稍后重试',
          loading: false
        });
      }
    });
  },

  // 修改文章列表请求方法
  fetchArticleList(page = 1) {
    if (this.data.articleLoading) return;

    this.setData({ articleLoading: true });

    // 保存当前滚动位置
    let scrollPos = 0;
    if (page > 1) {
      wx.createSelectorQuery()
        .selectViewport()
        .scrollOffset(function (res) {
          scrollPos = res.scrollTop;
        })
        .exec();
    }

    wx.request({
      url: 'https://www.haoyuming.online/api/user/article/latest',
      method: 'GET',
      data: {
        page: page,                    // 修改这里：current -> page
        pageSize: this.data.pageSize
      },
      success: (res) => {
        if (res.data.code === 200) {
          const { records, total } = res.data.data;

          const formattedArticles = records.map((article, index) => ({
            ...article,
            createTime: this.formatDate(article.createTime),
            uniqueKey: `${article.id}-${Date.now()}-${index}-${page}`
          }));

          let newArticles;
          if (page === 1) {
            newArticles = formattedArticles;
          } else {
            newArticles = [...this.data.articles, ...formattedArticles];
          }

          const hasMore = newArticles.length < total;

          this.setData({
            articles: newArticles,
            currentPage: page,
            total: total,
            hasMore: hasMore,
            articleLoading: false
          }, () => {
            // 在数据更新后恢复滚动位置
            if (page > 1) {
              wx.pageScrollTo({
                scrollTop: scrollPos,
                duration: 0
              });
            }
          });

          console.log('加载状态：', {
            currentPage: page,
            articleCount: newArticles.length,
            totalArticles: total,
            hasMore: hasMore
          });
        } else {
          this.setData({
            articleError: res.data.message || '获取文章列表失败',
            articleLoading: false
          });
        }
      },
      fail: (err) => {
        console.error('获取文章列表失败：', err);
        this.setData({
          articleError: '网络错误，请稍后重试',
          articleLoading: false
        });
      }
    });
  },

  // 获取最新文章列表
  fetchLatestArticles(page = 1) {
    if (this.data.loading) return;

    this.setData({ loading: true });

    wx.request({
      url: 'https://www.haoyuming.online/api/user/article/latest',
      method: 'GET',
      data: {
        page: page,
        pageSize: this.data.pageSize
      },
      success: (res) => {
        if (res.data.code === 200) {
          const { records, total } = res.data.data;

          // 格式化文章数据
          const formattedArticles = records.map(article => ({
            ...article,
            createTime: this.formatDate(article.createTime)
          }));

          // 如果是第一页，直接替换数据
          // 如果不是第一页，追加数据
          this.setData({
            articles: page === 1 ? formattedArticles : [...this.data.articles, ...formattedArticles],
            currentPage: page,
            total: total,
            hasMore: this.data.articles.length + formattedArticles.length < total
          });
        }
      },
      fail: (err) => {
        console.error('获取文章列表失败：', err);
        wx.showToast({
          title: '加载失败，请重试',
          icon: 'none'
        });
      },
      complete: () => {
        this.setData({ loading: false });
      }
    });
  },

  // 格式化日期
  formatDate(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
  },

  // 生成随机颜色
  getRandomColor() {
    const colors = [
      '#E8F4D9', // 浅绿
      '#FCE6E6', // 浅红
      '#E6F3FF', // 浅蓝
      '#FFF3E6', // 浅橙
      '#F3E6FF', // 浅紫
      '#E6FFF3', // 薄荷
      '#FFF6E6', // 浅黄
      '#F5F5F5'  // 浅灰
    ];
    return colors[Math.floor(Math.random() * colors.length)];
  },

  // 显示自定义提示
  showCustomToast(title, duration = 2000) {
    this.setData({
      showToast: true,
      toastTitle: title,
      toastDuration: duration
    });
  },

  // 提示隐藏回调
  onToastHide() {
    this.setData({
      showToast: false,
      toastTitle: ''
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    // 添加轮播图切换动画
    this.setData({
      currentSwiperIndex: 0
    });

    // 添加刷新动画
    wx.showNavigationBarLoading();
    wx.showLoading({
      title: '刷新中...',
      mask: true
    });

    // 重置页面数据
    this.setData({
      currentPage: 1,
      hasMore: true,
      articles: []
    });

    // 同时刷新热门文章和文章列表
    Promise.all([
      new Promise((resolve) => {
        this.fetchHotArticles();
        resolve();
      }),
      new Promise((resolve) => {
        this.fetchArticleList(1);
        resolve();
      })
    ]).then(() => {
      // 停止所有刷新动画
      wx.hideNavigationBarLoading();
      wx.hideLoading();
      wx.stopPullDownRefresh();

      // 使用自定义 toast 显示刷新成功
      this.showCustomToast('内容已更新', 2000);
    }).catch(() => {
      // 发生错误时也需要停止动画
      wx.hideNavigationBarLoading();
      wx.hideLoading();
      wx.stopPullDownRefresh();
    });
  },

  // 修改上拉加载更多方法
  onReachBottom() {
    if (!this.data.hasMore) {
      console.log('没有更多数据了');
      return;
    }

    if (this.data.articleLoading) {
      console.log('正在加载中，跳过本次加载');
      return;
    }

    const nextPage = this.data.currentPage + 1;
    console.log('触发加载更多，准备加载第', nextPage, '页');
    this.fetchArticleList(nextPage);
  },

  // 点击热门文章
  onHotArticleTap(e) {
    const article = e.currentTarget.dataset.article;
    wx.navigateTo({
      url: `/pages/article-detail/article-detail?id=${article.id}`
    });
  },

  // 轮播图切换事件
  handleSwiperChange(e) {
    this.setData({
      currentSwiperIndex: e.detail.current
    });
  },

  // Navigate to category page
  navigateToCategory() {
    wx.navigateTo({
      url: '/pages/category/category'
    });
  },
  navigateToSearch() {
    wx.navigateTo({
      url: '/pages/search/search',
    })
  },

  // 点击文章
  onArticleTap(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/article-detail/article-detail?id=${id}`
    });
  },

  // 跳转到登录页面
  goToLogin() {
    wx.switchTab({
      url: '/pages/profile/profile',
    });
  },

  // 添加拖动相关方法
  onGifStart(e) {
    this.setData({
      isDragging: true
    });
  },

  onGifMove(e) {
    if (!this.data.isDragging) return;

    const touch = e.touches[0];
    let left = touch.clientX - 60; // 60 是图片宽度的一半
    let top = touch.clientY - 60;  // 60 是图片高度的一半

    // 限制不超出屏幕
    left = Math.max(0, Math.min(left, this.data.windowWidth - 120));
    top = Math.max(0, Math.min(top, this.data.windowHeight - 120));

    this.setData({
      buttonLeft: left,
      buttonTop: top
    });
  },

  onGifEnd() {
    this.setData({
      isDragging: false
    });
  },

  // 处理轮播图切换
  onSwiperChange(e) {
    this.setData({
      currentSwiperIndex: e.detail.current
    });
  },

  // 显示全屏GIF
  showFullScreenGif() {
    this.setData({ showFullGif: true });
    setTimeout(() => {
      this.setData({ showFullGif: false });
    }, 3000);
  },

  // 隐藏全屏GIF
  hideFullScreenGif() {
    this.setData({ showFullGif: false });
  },
});